<template>
  <div class="register-container">
    <div class="background-decoration"></div>
    <div class="register-content">
      <div class="register-box">
        <div class="system-title">
          <h1>用户注册</h1>
          <p class="subtitle">User Registration</p>
        </div>
        <el-form :model="registerForm" :rules="registerRules" ref="registerFormRef">
          <el-form-item label="用&ensp;户&ensp;名" prop="username">
            <el-input v-model="registerForm.username" placeholder="请输入用户名"></el-input>
          </el-form-item>
                <el-form-item label="手&ensp;机&ensp;号" prop="phone">
            <el-input v-model="registerForm.phone" placeholder="请输入手机号"></el-input>
          </el-form-item>
          
          <el-form-item label="密&emsp;&emsp;码 " prop="password">
            <el-input v-model="registerForm.password" type="password" placeholder="请输入密码" show-password></el-input>
          </el-form-item>
          
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input v-model="registerForm.confirmPassword" type="password" placeholder="请确认密码" show-password></el-input>
          </el-form-item>
          
          <el-form-item label="头像" prop="file">
            <el-upload
              class="avatar-uploader"
              action="#"
              :auto-upload="false"
              :show-file-list="false"
              :on-change="handleAvatarChange"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
            <div class="upload-tip">请上传头像图片</div>
          </el-form-item>
          
          <el-form-item label="验证码" prop="code">
            <div class="captcha-container">
              <el-input v-model="registerForm.code" placeholder="验证码" class="captcha-input"></el-input>
              <div class="captcha-img" @click="refreshCaptcha">
                <img v-if="captchaUrl" :src="captchaUrl" alt="验证码" />
                <div v-else class="captcha-loading">加载中...</div>
              </div>
            </div>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" :loading="loading" @click="handleRegister" class="register-button">注册</el-button>
            <el-button @click="goToLogin" class="login-button">返回登录</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<style scoped>
.register-container {
  min-height: 100vh;
  position: relative;
  background: linear-gradient(135deg, #f7fafc 0%, #e3f6f5 100%);
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
}

.background-decoration {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-image: 
    radial-gradient(circle at 20% 20%, rgba(100, 200, 180, 0.08) 0%, transparent 40%),
    radial-gradient(circle at 80% 80%, rgba(100, 200, 180, 0.08) 0%, transparent 40%),
    url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><circle cx="50" cy="50" r="40" stroke="rgba(100,200,180,0.05)" stroke-width="0.5" fill="none"/></svg>');
  background-size: cover, cover, 300px 300px;
  animation: backgroundFloat 20s linear infinite;
}

@keyframes backgroundFloat {
  from { background-position: 0 0, 0 0, 0 0; }
  to { background-position: 100px 100px, -100px -100px, 300px 300px; }
}

.register-content {
  position: relative;
  z-index: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
}

.register-box {
  width: 480px;
  padding: 38px 36px 32px 36px;
  background: rgba(255, 255, 255, 0.98);
  border-radius: 18px;
  box-shadow: 0 8px 32px rgba(100, 200, 180, 0.10);
  backdrop-filter: blur(10px);
  margin: 0 auto;
  transition: transform 0.3s ease;
}
.register-box:hover {
  transform: translateY(-5px);
  box-shadow: 0 12px 40px rgba(100, 200, 180, 0.16);
}

.system-title {
  text-align: center;
  margin-bottom: 32px;
}
.system-title h1 {
  font-size: 28px;
  color: #22577a;
  margin-bottom: 8px;
  font-weight: 700;
  letter-spacing: 2px;
}
.subtitle {
  font-size: 15px;
  color: #38a3a5;
  margin: 0;
  letter-spacing: 1px;
}

.el-form-item {
  margin-bottom: 18px;
}

.el-input :deep(.el-input__wrapper) {
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(100, 200, 180, 0.05);
}

.avatar-uploader {
  width: 120px;
  height: 120px;
  border: 1.5px dashed #b8e1dd;
  border-radius: 50%;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 0 auto 8px auto;
  background: #fafdff;
  transition: border-color 0.3s;
}
.avatar-uploader:hover {
  border-color: #38a3a5;
}
.avatar-uploader-icon {
  font-size: 32px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.avatar {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  object-fit: cover;
  display: block;
}
.upload-tip {
  text-align: center;
  color: #909399;
  font-size: 13px;
  margin-top: 5px;
}

.captcha-container {
  display: flex;
  align-items: center;
  gap: 12px;
}
.captcha-input {
  flex: 1;
  margin-right: 12px;
}
.captcha-img {
  width: 144px;
  height: 40px;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f7fa;
  border-radius: 6px;
  overflow: hidden;
  flex-shrink: 0;
  border: 1.5px solid #e3e8ee;
}
.captcha-img img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.captcha-loading {
  font-size: 12px;
  color: #909399;
}

.el-form-item:last-child {
  margin-bottom: 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.register-button {
  width: 48%;
  border-radius: 10px;
  height: 44px;
  font-size: 16px;
  font-weight: 500;
  letter-spacing: 1px;
  background: linear-gradient(90deg, #8fd6e1 0%, #b8e1dd 100%);
  border: none;
  color: #22577a;
  transition: all 0.3s;
}
.register-button:hover {
  background: linear-gradient(90deg, #b8e1dd 0%, #8fd6e1 100%);
  color: #38a3a5;
  transform: translateY(-1px);
}
.login-button {
  width: 48%;
  border-radius: 10px;
  height: 44px;
  font-size: 16px;
  font-weight: 500;
  letter-spacing: 1px;
  background: linear-gradient(90deg, #bfc6d1 0%, #e0e4ea 100%);
  border: none;
  color: #555;
  margin-left: 0;
  transition: all 0.3s;
}
.login-button:hover {
  background: linear-gradient(90deg, #e0e4ea 0%, #bfc6d1 100%);
  color: #333;
  transform: translateY(-1px);
}

::-webkit-scrollbar {
  width: 8px;
  background: #e3f6f5;
}
::-webkit-scrollbar-thumb {
  background: #b8e1dd;
  border-radius: 4px;
}
</style>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { userApi } from '../api'

const router = useRouter()
const registerFormRef = ref(null)
const loading = ref(false)
const captchaUrl = ref('')
const verifyCodeKey = ref('')
const imageUrl = ref('')
const avatarFile = ref(null)

const registerForm = ref({
  username: '',
  password: '',
  confirmPassword: '',
  code: '',
  codekey: '',
  phone: '',
  file: null  // 添加file字段用于表单验证
})

const validatePass = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else {
    if (registerForm.value.confirmPassword !== '') {
      registerFormRef.value.validateField('confirmPassword')
    }
    callback()
  }
}

const validatePass2 = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== registerForm.value.password) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}

const registerRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    // { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  password: [
    { required: true, validator: validatePass, trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, validator: validatePass2, trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ],
  file: [
    { required: true, message: '请上传头像', trigger: 'change', validator: (rule, value, callback) => {
      if (!avatarFile.value) {
        callback(new Error('请上传头像'))
      } else {
        callback()
      }
    }}
  ]
}

// 获取验证码
const getCaptcha = async () => {
  try {
    const response = await userApi.getKaptcha()
    
    
    // 将Blob转换为JSON
    const text = await response.text()
    const data = JSON.parse(text)
    
    if (data.code === 200 && data.data) {
      // 从base64字符串创建图片URL
      captchaUrl.value = `data:image/jpeg;base64,${data.data.image}`
      
      // 获取验证码key
      const verifyCode = data.data.verifyCode
      if (verifyCode) {
        verifyCodeKey.value = verifyCode
        registerForm.value.codekey = verifyCode
      }
    } else {
    
      ElMessage.warning('验证码获取异常，请刷新重试')
    }
  } catch (error) {
  
    ElMessage.error('获取验证码失败')
  }
}

// 刷新验证码
const refreshCaptcha = () => {
  getCaptcha()
}

// 处理头像上传
const handleAvatarChange = (file) => {
  avatarFile.value = file.raw
  imageUrl.value = URL.createObjectURL(file.raw)
  registerForm.value.file = file.raw  // 更新表单中的file字段
}

// 注册处理
const handleRegister = async () => {
  if (!registerFormRef.value) return
  
  await registerFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        const formData = new FormData()
        const userInfo = {
          username: registerForm.value.username,
          password: registerForm.value.password,
          code: registerForm.value.code,
          codekey: registerForm.value.codekey,
          phone: registerForm.value.phone
        }
        
        formData.append('file', avatarFile.value)
        formData.append('users', new Blob([JSON.stringify(userInfo)], { type: 'application/json' }))
        
        const res = await userApi.register(formData)
        if (res.code === 200) {
          ElMessage.success(res.message || '注册成功')
          router.push('/login')
        } else {
          ElMessage.error(res.message || '注册失败，请检查输入信息')
          // 验证码错误时刷新验证码并清空输入框
          if (res.message && res.message.includes('验证码')) {
            registerForm.value.code = ''
            getCaptcha()
          }
        }
      } catch (error) {
        ElMessage.error(error.response?.data?.message || '注册失败，请稍后重试')
        console.error(error)
        // 发生错误时也刷新验证码
        registerForm.value.code = ''
        getCaptcha()
      } finally {
        loading.value = false
      }
    }
  })
}

// 返回登录页
const goToLogin = () => {
  router.push('/login')
}

onMounted(() => {
  getCaptcha()
})
</script>
